﻿using BUGCOME.Infrastructure;
using BUGCOME.Infrastructure.Attribute;
using BUGCOME.Model.Auth;
using BUGCOME.Model.Auth.dto;
using BUGCOME.ServiceCore.Services.IServices;
using System.Collections;

namespace BUGCOME.ServiceCore.Services
{
    /// <summary>
    /// 角色管理服务实现类，实现IRoleService接口
    /// </summary>
    [AppService(ServiceType = typeof(IRoleService), ServiceLifetime = LifeTime.Transient)]
    public class RoleService : BaseService<Role>, IRoleService
    {
        // 角色菜单服务
        private readonly IRoleMenuService roleMenuService;

        // 构造函数，注入角色菜单服务
        public RoleService(IRoleMenuService roleMenuService)
        {
            this.roleMenuService = roleMenuService;
        }

        /// <summary>
        /// 插入角色与菜单关联
        /// </summary>
        public async Task<long> InsertRoleMenuAsync(RoleDto roleDto)
        {
            long rows = 1;
            // 角色菜单关联列表
            List<RoleMenu> sysRoleMenus = new();
            // 遍历菜单ID，构建关联实体
            foreach (var item in roleDto.MenuIds)
            {
                RoleMenu rm = new()
                {
                    MenuId = item,
                    RoleId = roleDto.RoleId,
                    CreateBy = roleDto.CreateBy,
                    CreateTime = DateTime.Now
                };
                sysRoleMenus.Add(rm);
            }
            // 批量添加角色菜单关联
            if (sysRoleMenus.Count > 0)
            {
                rows = await roleMenuService.AddRoleMenuAsync(sysRoleMenus);
            }

            return rows;
        }

        /// <summary>
        /// 判断用户是否为管理员
        /// </summary>
        /// <param name="userid">用户ID</param>
        /// <returns>是否为管理员的异步任务</returns>
        public async Task<bool> IsAdminAsync(long userid)
        {
            List<string> roles = await SelectUserRoleKeysAsync(userid);
            return ((IList)roles).Contains(GlobalConstant.AdminRole);
        }

        /// <summary>
        /// 获取用户的角色权限字符串集合
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>角色权限字符串列表的异步任务</returns>
        public async Task<List<string>> SelectUserRoleKeysAsync(long userId)
        {
            List<Role> list = await SelectUserRoleListByUserIdAsync(userId);
            return list.Select(x => x.RoleKey).ToList();
        }

        /// <summary>
        /// 查询指定用户的角色列表（缓存10分钟）
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>角色列表的异步任务</returns>
        public async Task<List<Role>> SelectUserRoleListByUserIdAsync(long userId)
        {
            return await Context.Queryable<UserRole>()
               .LeftJoin<Role>((ur, r) => ur.RoleId == r.RoleId)
               .Where((ur, r) => ur.UserId == userId && r.RoleId > 0)
               .WithCache(60 * 10) // 缓存10分钟
               .Select((ur, r) => r)
               .ToListAsync();
        }

        /// <summary>
        /// 查询用户的有效角色ID列表（过滤状态为0的角色）
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>角色ID列表的异步任务</returns>
        public async Task<List<long>> SelectUserRolesAsync(long userId)
        {
            var list = (await SelectUserRoleListByUserIdAsync(userId)).Where(f => f.Status == 0);
            return list.Select(x => x.RoleId).ToList();
        }


       
    }
}